﻿using Assets.Core.Common.Web;
using Essensoft.Paylink.WeChatPay;
using Essensoft.Paylink.WeChatPay.V3;
using Essensoft.Paylink.WeChatPay.V3.Domain;
using Essensoft.Paylink.WeChatPay.V3.Request;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Nucleic.Core.DoMain;
using Nucleic.Core.Utils;
using Nucleic.Web.Models.WeChatPay;

namespace Nucleic.Web.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class WeChatPayV3Controller : ControllerBase
    {
        private readonly ILogger<WeChatPayV3Controller> _logger;
        private readonly IWeChatPayClient _client;
        private readonly IOptions<WeChatPayOptions> _optionsAccessor;
        /// <summary>
        /// h5支付
        /// </summary>
        /// <param name="viewModel"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("H5Pay")]
        public async Task<Result> H5Pay(WeChatPayH5PayV3ViewModel viewModel)
        {
            var book = SqlSugarFactory.Instance.Queryable<book_info>().First(x => x.appo_id == viewModel.appo_id);
            if (book == null)
            {
                return Result.fail("预约异常");
            }
            if (book.status != "0")
            {
                return Result.fail("订单状态,无需支付");
            }
            var item = SqlSugarFactory.Instance.Queryable<check_item>().First(x => x.item_id == book.item_id);
            var appo_id = SqlSugarFactory.Instance.Insertable(book).ExecuteReturnIdentity();

            //生成支付链接
            var model = new WeChatPayTransactionsH5BodyModel
            {
                AppId = _optionsAccessor.Value.AppId,
                MchId = _optionsAccessor.Value.MchId,
                Amount = new Amount { Total = (int)item.price * 100, Currency = "CNY" },
                Description = "核酸",
                NotifyUrl = Request.Scheme + "://" + Request.Host.Host + ":" + Request.Host.Port + "/wechatpay/v3/notify/transactions",
                OutTradeNo = book.orders_id,
                SceneInfo = new SceneInfo { PayerClientIp = "127.0.0.1", H5Info = new H5Info { Type = "Wap" } }
            };

            var request = new WeChatPayTransactionsH5Request();
            request.SetBodyModel(model);

            var response = await _client.ExecuteAsync(request, _optionsAccessor.Value);

            // h5_url为拉起微信支付收银台的中间页面，可通过访问该url来拉起微信客户端，完成支付,h5_url的有效期为5分钟。
            // https://pay.weixin.qq.com/wiki/doc/apiv3/apis/chapter3_3_4.shtml
            return Result.success(response.Body);
        }
    }
}
